﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Eqwww.Data;
using Eqwww.Domain.Models.SystemManage;
using Eqwww.Code;
using Eqwww.App.SystemManage;
using Eqwww.Web.Areas.SystemManage.Models.Post;
using System.Text;
using Eqwww.App.Authorize;

namespace Eqwww.Web.Areas.SystemManage.Controllers
{
    [Area("SystemManage")]
    public class PostController : ControllerBase
    {
        private PostApp _postApp;
        private AuthorizeApp _authorizeApp;
        private OrganizeApp _organizeApp;

        public PostController(PostApp postApp, AuthorizeApp authorizeApp, OrganizeApp organizeApp)
        {
            _postApp = postApp;
            _authorizeApp = authorizeApp;
            _organizeApp = organizeApp;
        }

        [AuthFilter]
        public IActionResult Index()
        {
            var currentModuleCode = "SystemManage_Post";
            ViewData["SelectedButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Selected);
            ViewData["InitialButtons"] = _authorizeApp.GetAuthorizedModuleButtons(User, currentModuleCode, ModuleButtonPosition.Initial);

            return View();
        }

        public IActionResult IndexGridJson(string keyword, string organizeKeyword, string jobKeyword, Pagination pagination)
        {
            var data = new
            {
                rows = from p in _postApp.GetPagedList(keyword, organizeKeyword, jobKeyword, pagination)
                       select new
                       {
                           p.Id,
                           p.Name,
                           p.Code,
                           p.SortCode,
                           p.CreateTime,
                           CreateUser=p.CreateUser.RealName,
                           Parent=p.Parent?.Name,
                           Organize=p.Organize?.Name,
                           Job=p.Job?.Name
                       },
                total = pagination.total,
                page = pagination.page,
                records = pagination.records
            };
            return Content(data.ToJson());
        }

        [AuthFilter]
        public async Task<IActionResult> Details(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var postModel = await _postApp.GetAsync(id, true);
            if (postModel == null)
            {
                return NotFound();
            }
            var postPath = _organizeApp.GetAncestorNamesString(postModel.OrganizeId) + "/" + postModel.Name;
            ViewData["PostPath"] = postPath;

            return View(postModel);
        }

        [AuthFilter]
        public IActionResult Create()
        {
            return View();
        }


        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Code,Name,JobId,JobName,OrganizeId,OrganizeName,ParentId,ParentName,SortCode")] CreateVIewModel postModel)
        {
            if (ModelState.IsValid)
            {
                var model = new PostModel
                {
                    Code = postModel.Code,
                    Name = postModel.Name,
                    ParentId = postModel.ParentId,
                    OrganizeId = postModel.OrganizeId,
                    JobId = postModel.JobId,
                    SortCode = postModel.SortCode
                };
                return Json(await _postApp.CreateAsync(model));
            }

            return Json(Common.ModelStateErrorResult(ModelState));
        }

        [AuthFilter]
        public async Task<IActionResult> Edit(string id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var postModel = await _postApp.GetAsync(id);
            if (postModel == null)
            {
                return NotFound();
            }
            var edit = new EditViewModel
            {
                Id = postModel.Id,
                Code = postModel.Code,
                Name = postModel.Name,
                ParentId = postModel.ParentId,
                ParentName = postModel.Parent == null ? null : postModel.Parent.Name,
                OrganizeId = postModel.OrganizeId,
                OrganizeName = postModel.Organize == null ? null : postModel.Organize.Name,
                JobId = postModel.JobId,
                JobName = postModel.Job == null ? null : postModel.Job.Name,
                SortCode = postModel.SortCode
            };
            return View(edit);
        }


        [HttpPost]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(string id, [Bind("Id,Code,Name,JobId,JobName,OrganizeId,OrganizeName,ParentId,ParentName,SortCode")] EditViewModel postModel)
        {
            if (id != postModel.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                var edit = await _postApp.GetAsync(id);
                edit.Code = postModel.Code;
                edit.Name = postModel.Name;
                edit.ParentId = postModel.ParentId;
                edit.OrganizeId = postModel.OrganizeId;
                edit.JobId = postModel.JobId;
                edit.SortCode = postModel.SortCode;
                edit.Parent = null;
                edit.Job = null;
                edit.Organize = null;
                return Json(await _postApp.UpdateAsync(edit));
            }
            return Error(ModelState.ErrorCount.ToString());
        }



        // POST: SystemManage/Post/Delete/5
        [HttpPost, ActionName("Delete")]
        [ExceptionFilter]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(string id)
        {
            return Json(await _postApp.RemoveAsync(id));
        }

        public IActionResult TreeCollapse()
        {
            ViewData["Items"] = _postApp.GetPostTreeCollapseItems();
            return View();
        }

        public IActionResult TreeCollapseToggle()
        {
            ViewData["Items"] = _postApp.GetPostTreeCollapseToggleItems();
            return View();
        }
    }
}
